//
//  FeedBackTextView.m
//  CarLifes
//
//  Created by yu on 2017/8/16.
//  Copyright © 2017年 jpas. All rights reserved.
//

#import "FeedBackTextView.h"

@interface FeedBackTextView ()<UITextViewDelegate>

@end

@implementation FeedBackTextView

- (instancetype)initWithCoder:(NSCoder *)aDecoder
{
    if (self = [super initWithCoder:aDecoder])
    {
        if (@available(iOS 13.0, *)) {
            self.textColor = UIColor.labelColor;
        } else {
            self.textColor = kTextBlackColor;
        }
        self.delegate = self;
        [self configSubview];
    }
    return self;
}

- (void)configSubview
{
    self.font = [UIFont systemFontOfSize:15];
    self.scrollEnabled = NO;
    
    _placeholderLabel = [[UILabel alloc] init];
    _placeholderLabel.text = @"请输入您的宝贵意见...";
    _placeholderLabel.font = [UIFont systemFontOfSize:15];
    if (@available(iOS 13.0, *)) {
        _placeholderLabel.textColor = UIColor.tertiaryLabelColor;
    } else {
        _placeholderLabel.textColor = kTextLightGrayColor;
    }
    
    _numLabel = [[UILabel alloc] init];
    _numLabel.text = @"0/200";
    _numLabel.numberOfLines = 2;
    _numLabel.textAlignment = NSTextAlignmentCenter;
    _numLabel.font = [UIFont systemFontOfSize:14];
    _numLabel.textColor = kTextLightGrayColor;
    
    [self sd_addSubviews:@[_placeholderLabel,_numLabel]];
    
    _placeholderLabel.sd_layout
    .topSpaceToView(self, 5)
    .leftSpaceToView(self, 5)
    .rightSpaceToView(self, 5)
    .heightIs(25);
    
    [_numLabel setSingleLineAutoResizeWithMaxWidth:100];
    _numLabel.sd_layout
    .rightSpaceToView(self, 10)
    .bottomSpaceToView(self, 5)
    .heightIs(20);
    
    self.layer.masksToBounds = YES;
    self.layer.borderWidth = 0.5;
    self.layer.borderColor = kTextLightGrayColor.CGColor;
    
}

#pragma mark - UITextViewDelegate

- (void)textViewDidChange:(UITextView *)textView
{
    long long remainNum;
    NSString *textContent;
    if (textView.text.length == 0) {
        _placeholderLabel.text = @"请输入您的宝贵意见...";
        _numLabel.text = [NSString stringWithFormat:@"0/200"];
    }else if(textView.text.length >= 200){
        textView.text = [textView.text substringToIndex:200];
        _placeholderLabel.text = @"";
        _numLabel.text = [NSString stringWithFormat:@"200/0"];
    }else{
        _placeholderLabel.text = @"";
        textContent = textView.text;
        long long existNum = [textContent length];
        remainNum = 200 - existNum;
        _numLabel.text = [NSString stringWithFormat:@"%lld/%lld",existNum,remainNum];
    }
}

- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    [textView scrollRangeToVisible:NSMakeRange(textView.text.length, 1)];
    if(range.location >= 200){
        return NO;
    }
    return YES;
}

@end
